package com.wcy.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCodeImageGenerator {
    private static final char[] CHAR_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    public char[] generateVerifyCode(){
        Random random = new Random();
        char[] res = new char[4];
        for (int i = 0; i < res.length; i++) {
            res[i]= CHAR_ARRAY[random.nextInt(CHAR_ARRAY.length)];
        }
        return res;
    }

    public BufferedImage generate(char[] codes){
        Random random = new Random();
        BufferedImage bufferedImage = new BufferedImage(128,64,BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();
        Font font = new Font("华文行楷", Font.BOLD + Font.ITALIC, 30);
        g.setColor(Color.GRAY);
        g.fillRect(0,0,128,64);
        g.setFont(font);
        for (int i = 0; i < 100; i++){
            g.setColor(new Color(random.nextInt(155),random.nextInt(155),random.nextInt(155)));
            g.drawLine(random.nextInt(128),random.nextInt(64),random.nextInt(128),random.nextInt(64));
        }

        for (int i = 0; i < codes.length; i++) {
            g.setColor(new Color(100+random.nextInt(155),100+random.nextInt(155),100+random.nextInt(155)));
            g.drawChars(codes,i,1,5+i*30+random.nextInt(10),30+random.nextInt(20));
        }
        for (int i = 0; i < 10; i++){
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            g.drawLine(random.nextInt(128),random.nextInt(64),random.nextInt(128),random.nextInt(64));
        }

        return bufferedImage;
    }
}
